package org.example.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.example.pojo.Result;
import org.example.properties.AuthWhiteName;
import org.example.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.util.List;

import static javax.management.Query.match;
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthWhiteName authWhiteName;
    //private List<String> whiteUrl=List.of("/user/login", "/user/register");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(match(path,authWhiteName.getUrl())) {
            return chain.filter(exchange);
        }
        //然后就开始验证token
        String token=request.getHeaders().getFirst("user_token");
        if(token==null || token.length()==0) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims = JWTUtils.parseJWT(token);
        if(claims==null) {
            log.info("令牌解析错误");
            return unauthorizedResponse(exchange, "令牌解析错误");
        }

        return chain.filter(exchange);
    }

    /**
     * 返回一些出错的信息，将状态码和其他的信息一起返回
     * @param exchange
     * @param message
     * @return
     */
    @SneakyThrows
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message) {
        log.error("[用户认证失败],url:{}",exchange.getRequest().getURI().getPath());
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_CBOR_VALUE);
        Result result= Result.fail(message);
        DataBuffer dataBuffer=response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));
    }

    private boolean match(String path, List<String> whiteUrl) {
        if(path==null || whiteUrl.size()==0) {
            return false;
        }
        return whiteUrl.contains(path);
    }

    @Override
    public int getOrder() {
        //值越小优先级越高
        return -200;
    }
}
